package com.yeeverse.sdk.callback;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yeeverse.sdk.exception.SdkException;
import com.yeeverse.sdk.util.*;

import java.util.Map;

/**
 * 回调处理类
 */
public class CallbackHandler {

    /**
     * 回调处理方法
     *
     * @param callbackData       回调数据
     * @param merchantPrivateKey 商户rsa私钥
     * @return 解密后的数据数据
     */
    public static Map<String, String> process(String callbackData, String merchantPrivateKey) {

        try {
            String safeDecodeString = Base64Util.getSafeDecodeString(callbackData);
            Map<String, String> map = JsonUtils.fromJsonString(safeDecodeString, new TypeReference<Map<String, String>>() {
            });
            String data = map.get("data");
            if (StringUtils.isBlank(data)) {
                throw new RuntimeException("回调处理异常，data is empty");
            }

            String aesKeyStr = map.get("aesKey");
            if (StringUtils.isBlank(aesKeyStr)) {
                throw new RuntimeException("回调处理异常,aesKey is empte");
            }

            String aesKey = RSAUtils.decryptByPrivateKey(aesKeyStr, merchantPrivateKey);

            String decrypt = AES128CBC.decrypt(data, aesKey);

            if (StringUtils.isBlank(decrypt)) {
                throw new SdkException("回调处理异常,data is empte");
            }

            return JsonUtils.fromJsonString(decrypt, new TypeReference<Map<String, String>>() {
            });
        } catch (Exception e) {
            throw new SdkException("回调未知异常," + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Map<String, String> process = process("{\"data\":\"l3duuyA0W58+nzr2ce1SYQkmUf8zJV2WWtWdtHFQOqyW8/6lVsIx5oC5gJaxwY36z/SW9Yk5j28Cy8JJR2yEletp2kicA7yymd6yb2hG+RUR1pEdbzQuY5hFozWsdSdIO/j9HQlpA8Cx4byTFXbcswWE9PzKV77nHpRKvmVFb5Ds+5ZQ1tQVDNFdDKD1APUnAS7QEslxyeD9HzeQuLOcESQFjd3mpYOl0P+dnPEHVtW4ovoK0VXCueZdaBcPDHl/csS4CUbr6XEcrtjXbK8VT/PgIwTUELfoLpRD+TdSyf/UFVrd6hUSn+Zhdr9XideEnHoQs3UoiEx9CdfYfrNzbOLTnouBjNclhmH8YqaE5cNu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